import {InboxOutlined, LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import {request} from "@umijs/max";
import {Upload, message} from "antd";
import {forwardRef, useImperativeHandle, useRef, useState} from "react";
import './index.less'

export async function upload(
  data: FormData,
  options?: { [key: string]: any },
) {
  return request<{
    code: number;
    data: Record<string, any>;
    msg?: string;
  }>('/engine-service/api/v1/file/upload', {
    method: 'POST',
    data,
    ...(options || {}),
  });
}

const CustomDraggedUpload = (props: any, ref: any) => {
  // const [upLoading, setLoading] = useState(false);

  console.log(props.value)

  useImperativeHandle(ref, () => ({}))

  return <Upload.Dragger
    fileList={props.value}
    maxCount={1}
    // onChange={props?.onChange}
    // listType="picture-card"
    // showUploadList={false}
    beforeUpload={(file) => {
      console.log(file)
      const isJmx = file.name.endsWith(".jmx");
      if (!isJmx) {
        message.error(`${file.name} 不是jmx文件`);
      }
      return isJmx || Upload.LIST_IGNORE
    }}
    onRemove={() => {
      // console.log('file', file);
      // const newFileList = fileList?.filter((item: any) => item?.uid !== file.uid)
      props?.onChange?.()
    }}
    customRequest={async (file) => {
      try {
        const formData = new FormData()
        formData.append("file", file.file)
        formData.append("type", props.type || 'banner')
        const res = await upload(formData)
        // console.log(res);
        // console.log(props);
        props?.onChange?.([{
          url: res.data?.url,
          status: 'done',
          uid: (file?.file as any)?.uid,
          name: (file?.file as any)?.name,
          size: res?.data?.size,
        }])
        // console.log(imgKeyMapRef, res.data);

        // setLoading(false)
      } catch (e) {
        // setLoading(false)
      }
    }}
    className='custom_dragger_upload'
    style={props.style}

  >
    <p className="ant-upload-drag-icon">
      <InboxOutlined/>
    </p>
    <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
    <p className="ant-upload-hint">
      仅支持单次上传后缀为.jmx格式的文件。严禁上传公司数据或其他被禁止的文件。
    </p>
  </Upload.Dragger>
}

export default forwardRef(CustomDraggedUpload)
